
package swb.api.com.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import swb.api.com.repository.WithdrawAccountRepository;
import swb.api.com.repository.dto.WithdrawAccount;
import swb.api.com.service.WithdrawAccountService;
import swb.api.com.vo.req.BindAccountRequest;
import swb.api.com.vo.resp.BindAccountResponse;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 提现账户服务实现类
 * 提供用户绑定提现账户、查询账户列表、设置默认账户和解绑账户等功能
 */
@Slf4j
@Service
@Transactional
public class WithdrawAccountServiceImpl implements WithdrawAccountService {

    @Autowired
    private WithdrawAccountRepository withdrawAccountRepository;

    /**
     * 绑定提现账户
     *
     * @param userId  用户ID
     * @param request 绑定账户请求参数，包含账户类型、真实姓名和账户号码等信息
     * @return BindAccountResponse 绑定结果响应对象，包含操作是否成功和相关消息
     */
    @Override
    public BindAccountResponse bindAccount(Long userId, BindAccountRequest request) {
        BindAccountResponse response = new BindAccountResponse();

        try {
            // 验证账户类型
            if (request.getAccountType() != 1 && request.getAccountType() != 2) {
                response.setSuccess(false);
                response.setMessage("账户类型无效");
                return response;
            }

            // 检查是否已绑定相同类型的账户
            Optional<WithdrawAccount> existingAccount = withdrawAccountRepository
                    .findByUserIdAndAccountTypeAndStatus(userId, request.getAccountType(), 1);

            if (existingAccount.isPresent()) {
                response.setSuccess(false);
                response.setMessage("该类型账户已绑定");
                return response;
            }

            // 创建新的提现账户
            WithdrawAccount account = new WithdrawAccount();
            account.setUserId(userId);
            account.setAccountType(request.getAccountType());
            account.setRealName(request.getRealName());
            account.setAccountNo(request.getAccountNo());
            account.setIsDefault(0); // 默认非默认账户
            account.setStatus(1); // 正常状态
            account.setCreatedAt(LocalDateTime.now());
            account.setUpdatedAt(LocalDateTime.now());

            // 如果是第一个账户，设为默认账户
            long accountCount = withdrawAccountRepository.countByUserId(userId);
            if (accountCount == 0) {
                account.setIsDefault(1);
            }

            WithdrawAccount savedAccount = withdrawAccountRepository.save(account);

            response.setSuccess(true);
            response.setMessage("账户绑定成功");
            response.setAccountId(savedAccount.getId());

        } catch (Exception e) {
            response.setSuccess(false);
            response.setMessage("账户绑定失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 获取用户的提现账户列表
     *
     * @param userId 用户ID
     * @return List<WithdrawAccount> 用户的所有提现账户列表
     */
    @Override
    public List<WithdrawAccount> getUserAccounts(Long userId) {
        return withdrawAccountRepository.findByUserId(userId);
    }

    /**
     * 设置默认提现账户
     *
     * @param userId    用户ID
     * @param accountId 要设为默认的账户ID
     * @return boolean 操作是否成功
     */
    @Override
    public boolean setDefaultAccount(Long userId, Long accountId) {
        // 将用户其他账户设为非默认
        withdrawAccountRepository.updateIsDefaultByUserId(userId, 0);

        // 将指定账户设为默认
        Optional<WithdrawAccount> accountOpt = withdrawAccountRepository
                .findByUserIdAndIdAndStatus(userId, accountId, 1);

        if (accountOpt.isPresent()) {
            WithdrawAccount account = accountOpt.get();
            account.setIsDefault(1);
            account.setUpdatedAt(LocalDateTime.now());
            withdrawAccountRepository.save(account);
            return true;
        }

        return false;
    }

    /**
     * 解绑提现账户（逻辑删除）
     *
     * @param userId    用户ID
     * @param accountId 要解绑的账户ID
     * @return boolean 操作是否成功
     */
    @Override
    public boolean unbindAccount(Long userId, Long accountId) {
        Optional<WithdrawAccount> accountOpt = withdrawAccountRepository
                .findByUserIdAndIdAndStatus(userId, accountId, 1);

        if (accountOpt.isPresent()) {
            WithdrawAccount account = accountOpt.get();
            account.setStatus(0); // 禁用账户
            account.setUpdatedAt(LocalDateTime.now());
            withdrawAccountRepository.save(account);
            return true;
        }

        return false;
    }

    /**
     * 禁用提现账户
     *
     * @param userId    用户ID
     * @param accountId 账户ID
     * @return boolean 操作是否成功
     */
    @Override
    public boolean disableAccount(Long userId, Long accountId) {
        try {
            // 调用Repository方法禁用账户
            int result = withdrawAccountRepository.disableAccount(userId, accountId);
            return result > 0;
        } catch (Exception e) {
            // 记录日志或处理异常
            log.error("禁用账户异常: " + e.getMessage());
            return false;
        }
    }

    @Override
    public Page<WithdrawAccount> findAll(Pageable pageable) {
        return withdrawAccountRepository.findAll(pageable);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        WithdrawAccount account = withdrawAccountRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("账户不存在"));
        account.setStatus(status);
        withdrawAccountRepository.save(account);
    }

}